package com.sinog.biz.service.business.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinog.biz.config.param.Converse;
import com.sinog.biz.mapper.havexml.AreaCodeFullMapper;
import com.sinog.biz.mapper.havexml.ChangeTableMapper;
import com.sinog.biz.mapper.havexml.PrisaveTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerFxExcelTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainExcelTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainMapper;
import com.sinog.biz.mapper.havexml.PrisonerSrExcelTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerSrMapper;
import com.sinog.biz.mapper.havexml.PrisonerZnExcelTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerZnMapper;
import com.sinog.biz.service.business.SocialRelationsService;
import com.sinog.biz.util.CheckFieldValue;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.biz.util.DataUtils;
import com.sinog.biz.util.IdGen;
import com.sinog.biz.util.smlib.Sm4;
import com.sinog.core.domain.ChangeTable;
import com.sinog.core.domain.PrisaveTemp;
import com.sinog.core.domain.PrisonerMain;
import com.sinog.core.domain.PrisonerSr;
import com.sinog.core.domain.PrisonerSrExcelTemp;
import com.sinog.core.domain.PrisonerZn;
import com.sinog.core.domain.PrisonerZnExcelTemp;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.PageReturnUtil;
import com.sinog.core.util.PhoneUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @desc 社会关系实现类
 * @author -
 * @date -
 */
@Slf4j
@Service
public class SocialRelationsServiceImpl extends ServiceImpl<PrisonerZnMapper,PrisonerZn> implements SocialRelationsService {

    @Resource
    private PrisonerZnMapper prisonerZnMapper;
    @Resource
    private PrisonerZnExcelTempMapper prisonerZnExcelTempMapper;
    @Resource
    private PrisonerMainExcelTempMapper prisonerMainExcelTempMapper;
    @Resource
    private PrisonerSrMapper prisonerSrMapper;
    @Resource
    private PrisonerSrExcelTempMapper prisonerSrExcelTempMapper;
    @Resource
    private PrisonerFxExcelTempMapper prisonerFxExcelTempMapper;
    @Resource
    private PrisaveTempMapper prisaveTempMapper;
    @Resource
    private PrisonerMainMapper prisonerMainMapper;
    @Resource
    private AreaCodeFullMapper areaCodeFullMapper;
    @Resource
    private ChangeTableMapper changeTableMapper;

    /**
     * 保存未成年子女信息
     * @param data data
     * @param user user
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveNoAdult(String data,UserDTO user) {
        // 参数实体
        PrisonerZn prisonerZn = JsonUtil.toBean(data,PrisonerZn.class);
        if(prisonerZn.getZnsfId().trim().length() <= Constants.Number.NUM_EIGHTEEN) {
            prisonerZn.setZnsfId(Sm4.encryptEcb(prisonerZn.getZnsfId()));
        }
        Date date = new Date();
        prisonerZn.setName(prisonerZn.getName().trim());
        prisonerZn.setAdduserid(user.getDepartid());
        prisonerZn.setCreateTime(date);
        prisonerZn.setCreateUser(user.getAccount());
        prisonerZn.setUpdateTime(date);
        prisonerZn.setUpdateUser(user.getAccount());
        // 户籍所在省、市、县、街道名称
        String nativeproNameCodeId = prisonerZn.getNativepro();
        String nativecityNameCodeId = prisonerZn.getNativecity();
        String nativecouNameCodeId = prisonerZn.getNativecou();
        String nativevillNameCodeId = prisonerZn.getNativevill();
        Map<String,String> areaNames;
        if (StringUtils.isNotBlank(nativeproNameCodeId)){
            areaNames = areaCodeFullMapper.getAreaNames(nativeproNameCodeId,nativecityNameCodeId,nativecouNameCodeId,nativevillNameCodeId);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerZn.setNativeproName(areaNames.get("shengName"));
            prisonerZn.setNativecityName(areaNames.get("dishiName"));
            prisonerZn.setNativecouName(areaNames.get("quxianName"));
            prisonerZn.setNativevillName(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(nativecityNameCodeId)){
                prisonerZn.setNativecityName("");
            }
            if (StringUtils.isBlank(nativecouNameCodeId)){
                prisonerZn.setNativecouName("");
            }
            if (StringUtils.isBlank(nativevillNameCodeId)){
                prisonerZn.setNativevillName("");
            }
        } else {
            prisonerZn.setNativeproName("");
            prisonerZn.setNativecityName("");
            prisonerZn.setNativecouName("");
            prisonerZn.setNativevillName("");
        }
        // 居住地所在省、市、县、街道名称
        String placeproNameCodeId = prisonerZn.getPlacepro();
        String placecityNameCodeId = prisonerZn.getPlacecity();
        String placecouNameCodeId = prisonerZn.getPlacecou();
        String placevillNameCodeId = prisonerZn.getPlacevill();
        if (StringUtils.isNotBlank(placeproNameCodeId)){
            areaNames = areaCodeFullMapper.getAreaNames(placeproNameCodeId,placecityNameCodeId,placecouNameCodeId,placevillNameCodeId);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerZn.setPlaceproName(areaNames.get("shengName"));
            prisonerZn.setPlacecityName(areaNames.get("dishiName"));
            prisonerZn.setPlacecouName(areaNames.get("quxianName"));
            prisonerZn.setPlacevillName(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(placecityNameCodeId)){
                prisonerZn.setPlacecityName("");
            }
            if (StringUtils.isBlank(placecouNameCodeId)){
                prisonerZn.setPlacecouName("");
            }
            if (StringUtils.isBlank(placevillNameCodeId)){
                prisonerZn.setPlacevillName("");
            }
        } else {
            prisonerZn.setPlaceproName("");
            prisonerZn.setPlacecityName("");
            prisonerZn.setPlacecouName("");
            prisonerZn.setPlacevillName("");
        }
        String hujidi = prisonerZn.getNativeproName() + prisonerZn.getNativecityName() + prisonerZn.getNativecouName() + prisonerZn.getNativevillName() + prisonerZn.getNativenum();
        prisonerZn.setHujidi(hujidi);
        String juzhudi = prisonerZn.getPlaceproName() + prisonerZn.getPlacecityName() + prisonerZn.getPlacecouName() + prisonerZn.getPlacevillName() + prisonerZn.getPlacenum();
        prisonerZn.setJuzhudi(juzhudi);
        if(Constants.NumberStr.NUM_STR_FU_ONE.equals(prisonerZn.getPriNum())) {
            log.error("无罪犯编号，保存错误");
            return Result.failure(ReturnCode.SAVE_FAILED);
        }
        prisonerZn.setId(IdGen.strid());
        // 山西个性化功能:监测是否更新子女信息
        String localCode = CodeUrlUtils.getLocalCode();
        if(Constants.XzqhCode.SHAN1XI.equals(localCode) && StringUtils.equals(user.getLevel(),Constants.OrgLevel.LEVEL_SFS)){
            checkChangePrisonerZn(prisonerZn, user, Constants.SqlType.INSERT);
        }
        return prisonerZn.insert() ? Result.success() : Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 更新未成年子女信息
     * @param data data
     * @param user user
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateNoAdult(String data,UserDTO user) {
        // 参数实体
        PrisonerZn prisonerZn = JsonUtil.toBean(data,PrisonerZn.class);
        if(prisonerZn.getZnsfId().trim().length() <= Constants.Number.NUM_EIGHTEEN) {
            prisonerZn.setZnsfId(Sm4.encryptEcb(prisonerZn.getZnsfId()));
        }
        prisonerZn.setName(prisonerZn.getName().trim());
        prisonerZn.setUpdateTime(new Date());
        prisonerZn.setUpdateUser(user.getAccount());
        // 户籍所在省、市、县、街道名称
        String nativeproNameCodeId = prisonerZn.getNativepro();
        String nativecityNameCodeId = prisonerZn.getNativecity();
        String nativecouNameCodeId = prisonerZn.getNativecou();
        String nativevillNameCodeId = prisonerZn.getNativevill();
        Map<String,String> areaNames;
        if (StringUtils.isNotBlank(nativeproNameCodeId)){
            areaNames = areaCodeFullMapper.getAreaNames(nativeproNameCodeId,nativecityNameCodeId,nativecouNameCodeId,nativevillNameCodeId);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerZn.setNativeproName(areaNames.get("shengName"));
            prisonerZn.setNativecityName(areaNames.get("dishiName"));
            prisonerZn.setNativecouName(areaNames.get("quxianName"));
            prisonerZn.setNativevillName(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(nativecityNameCodeId)){
                prisonerZn.setNativecityName("");
            }
            if (StringUtils.isBlank(nativecouNameCodeId)){
                prisonerZn.setNativecouName("");
            }
            if (StringUtils.isBlank(nativevillNameCodeId)){
                prisonerZn.setNativevillName("");
            }
        } else {
            prisonerZn.setNativeproName("");
            prisonerZn.setNativecityName("");
            prisonerZn.setNativecouName("");
            prisonerZn.setNativevillName("");
        }
        // 居住地所在省、市、县、街道名称
        String placeproNameCodeId = prisonerZn.getPlacepro();
        String placecityNameCodeId = prisonerZn.getPlacecity();
        String placecouNameCodeId = prisonerZn.getPlacecou();
        String placevillNameCodeId = prisonerZn.getPlacevill();
        if (StringUtils.isNotBlank(placeproNameCodeId)){
            areaNames = areaCodeFullMapper.getAreaNames(placeproNameCodeId,placecityNameCodeId,placecouNameCodeId,placevillNameCodeId);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerZn.setPlaceproName(areaNames.get("shengName"));
            prisonerZn.setPlacecityName(areaNames.get("dishiName"));
            prisonerZn.setPlacecouName(areaNames.get("quxianName"));
            prisonerZn.setPlacevillName(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(placecityNameCodeId)){
                prisonerZn.setPlacecityName("");
            }
            if (StringUtils.isBlank(placecouNameCodeId)){
                prisonerZn.setPlacecouName("");
            }
            if (StringUtils.isBlank(placevillNameCodeId)){
                prisonerZn.setPlacevillName("");
            }
        } else {
            prisonerZn.setPlaceproName("");
            prisonerZn.setPlacecityName("");
            prisonerZn.setPlacecouName("");
            prisonerZn.setPlacevillName("");
        }
        String hujidi = prisonerZn.getNativeproName() + prisonerZn.getNativecityName() + prisonerZn.getNativecouName() + prisonerZn.getNativevillName() + prisonerZn.getNativenum();
        prisonerZn.setHujidi(hujidi);
        String juzhudi = prisonerZn.getPlaceproName() + prisonerZn.getPlacecityName() + prisonerZn.getPlacecouName() + prisonerZn.getPlacevillName() + prisonerZn.getPlacenum();
        prisonerZn.setJuzhudi(juzhudi);
        if(Constants.NumberStr.NUM_STR_FU_ONE.equals(prisonerZn.getPriNum())) {
            log.error("无罪犯编号，保存错误");
            return Result.failure(ReturnCode.SAVE_FAILED);
        }
        // 山西个性化需求:监测司法所是否更改未成年子女信息
        String localCode = CodeUrlUtils.getLocalCode();
        if(Constants.XzqhCode.SHAN1XI.equals(localCode) &&StringUtils.equals(user.getLevel(),Constants.OrgLevel.LEVEL_SFS)){
            checkChangePrisonerZn(prisonerZn, user,Constants.SqlType.UPDATE);
        }
        int a = prisonerZnMapper.updateById(prisonerZn);
        if(Constants.Number.NUM_ZERO < a) {
            String id = prisonerZn.getId();
            return Result.success(id);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 更新未成年子女信息excel
     * @param data data
     * @param user user
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateNoAdultExcel(String data,UserDTO user) {
        // 对前台传过来的数据进行二次处理
        PrisonerZnExcelTemp prisonerZn = JsonUtil.toBean(data,PrisonerZnExcelTemp.class);
        if(prisonerZn.getIdType() != null) {
            prisonerZn.setZnIdtype(prisonerZn.getIdType());
        }
        if(prisonerZn.getZnsfId().trim().length() <= Constants.Number.NUM_EIGHTEEN) {
            prisonerZn.setZnsfId(Sm4.encryptEcb(prisonerZn.getZnsfId()));
        }
        String name = prisonerZn.getName().trim();
        prisonerZn.setName(name);
        // 户籍所在省、市、县、街道名称
        String nativeproNameCodeId = prisonerZn.getNativepro();
        String nativecityNameCodeId = prisonerZn.getNativecity();
        String nativecouNameCodeId = prisonerZn.getNativecou();
        String nativevillNameCodeId = prisonerZn.getNativevill();
        Map<String,String> areaNames;
        if (StringUtils.isNotBlank(nativeproNameCodeId)){
            areaNames = areaCodeFullMapper.getAreaNames(nativeproNameCodeId,nativecityNameCodeId,nativecouNameCodeId,nativevillNameCodeId);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerZn.setNativeproName(areaNames.get("shengName"));
            prisonerZn.setNativecityName(areaNames.get("dishiName"));
            prisonerZn.setNativecouName(areaNames.get("quxianName"));
            prisonerZn.setNativevillName(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(nativecityNameCodeId)){
                prisonerZn.setNativecityName("");
            }
            if (StringUtils.isBlank(nativecouNameCodeId)){
                prisonerZn.setNativecouName("");
            }
            if (StringUtils.isBlank(nativevillNameCodeId)){
                prisonerZn.setNativevillName("");
            }
        } else {
            prisonerZn.setNativeproName("");
            prisonerZn.setNativecityName("");
            prisonerZn.setNativecouName("");
            prisonerZn.setNativevillName("");
        }
        // 居住地所在省、市、县、街道名称
        String placeproNameCodeId = prisonerZn.getPlacepro();
        String placecityNameCodeId = prisonerZn.getPlacecity();
        String placecouNameCodeId = prisonerZn.getPlacecou();
        String placevillNameCodeId = prisonerZn.getPlacevill();
        if (StringUtils.isNotBlank(placeproNameCodeId)){
            areaNames = areaCodeFullMapper.getAreaNames(placeproNameCodeId,placecityNameCodeId,placecouNameCodeId,placevillNameCodeId);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerZn.setPlaceproName(areaNames.get("shengName"));
            prisonerZn.setPlacecityName(areaNames.get("dishiName"));
            prisonerZn.setPlacecouName(areaNames.get("quxianName"));
            prisonerZn.setPlacevillName(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(placecityNameCodeId)){
                prisonerZn.setPlacecityName("");
            }
            if (StringUtils.isBlank(placecouNameCodeId)){
                prisonerZn.setPlacecouName("");
            }
            if (StringUtils.isBlank(placevillNameCodeId)){
                prisonerZn.setPlacevillName("");
            }
        } else {
            prisonerZn.setPlaceproName("");
            prisonerZn.setPlacecityName("");
            prisonerZn.setPlacecouName("");
            prisonerZn.setPlacevillName("");
        }
        if(Constants.NumberStr.NUM_STR_FU_ONE.equals(prisonerZn.getPriNum())) {
            log.error("无罪犯编号，保存错误");
            return Result.failure(ReturnCode.SAVE_FAILED);
        }
        prisonerZn.setCheckFlag("0");
        int a = prisonerZnExcelTempMapper.updateById(prisonerZn);
        if(0 < a) {
            //mainCount>0说明数据未填写完整
            //mainCount=0说明数据已经完整
            //当下面四个值都为0就设置主表的success_flag=0；
            int mainCount = prisonerMainExcelTempMapper.selectMainByCheckFlag(prisonerZn.getPriNum());
            int fxCount = prisonerFxExcelTempMapper.selectFxByCheckFlag(prisonerZn.getPriNum());
            int srCount = prisonerSrExcelTempMapper.selectSrByCheckFlag(prisonerZn.getPriNum());
            if(mainCount + fxCount + srCount == 0) {
                prisonerMainExcelTempMapper.updateMainSuccessFlag(prisonerZn.getPriNum());
            }
            String id = prisonerZn.getId();
            return Result.success(id);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 预安置人员信息录入 - 获取未成年子女列表信息
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param querykey querykey
     * @return String
     */
    @Override
    public String getNoAdultList(Integer pageIndex,Integer pageSize,
                                 @Converse(caseIf = "-1", converseTo = "0") String querykey) {
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page = page.setRecords(prisonerZnMapper.getNoAdultList(page,querykey));
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 预安置人员信息录入 - 获取未成年子女列表信息excel
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param querykey querykey
     * @return String
     */
    @Override
    public String getNoAdultListExcel(Integer pageIndex,Integer pageSize,
                                      @Converse(caseIf = "-1", converseTo = "0") String querykey) {
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page = page.setRecords(prisonerZnExcelTempMapper.getNoAdultList(page,querykey));
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 根据id获取未成年子女的信息
     * @param id id
     * @return String
     */
    @Override
    public String getInfoById(String id) {
        PrisonerZn prisonerZn = prisonerZnMapper.selectById(id);
        // 目的将Long类型的id转成字符串类型（否则传入到前台的值不正确）
        String text = JsonUtil.toText(prisonerZn);
        Map<String,Object> map = JsonUtil.toMap(text);
        String idstr = map.get("id").toString();
        map.put("id",idstr);
        return JsonUtil.toText(map);
    }

    /**
     * 根据id获取未成年子女的信息excel
     * @param id id
     * @return String
     */
    @Override
    public String getInfoByIdExcel(String id) {
        PrisonerZnExcelTemp prisonerZn = prisonerZnExcelTempMapper.selectById(id);
        // 目的将Long类型的id转成字符串类型（否则传入到前台的值不正确）
        String text = JsonUtil.toText(prisonerZn);
        Map<String,Object> map = JsonUtil.toMap(text);
        String idstr = map.get("id").toString();
        if(null != map.get("znIdtype")) {
            map.put("idType",map.get("znIdtype"));
        }
        map.put("id",idstr);
        return JsonUtil.toText(map);
    }

    /**
     * 删除未成年子女信息（逻辑删除）标志改为-1
     * @param id id
     * @return Result
     */
    @Override
    public Result deleteNoAultById(String id) {
        int row = prisonerZnMapper.updataDelFlag(id);
        if(0 < row) {
            return Result.success("删除成功");
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 删除未成年子女信息（逻辑删除）标志改为-1excel
     * @param id id
     * @return Result
     */
    @Override
    public Result deleteNoAultByIdExcel(String id) {
        int row = prisonerZnExcelTempMapper.deleteById(id);
        if(0 < row) {
            return Result.success("删除成功");
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 添加社会关系
     * @param data data
     * @param user user
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveSrInfo(String data,UserDTO user) {
        // 参数实体
        PrisonerSr prisonerSr = JsonUtil.toBean(data,PrisonerSr.class);
        Date date = new Date();
        prisonerSr.setThename(prisonerSr.getThename().trim());
        if(prisonerSr.getIdnumber().trim().length() <= Constants.Number.NUM_EIGHTEEN) {
            prisonerSr.setIdnumber(Sm4.encryptEcb(prisonerSr.getIdnumber()));
        }
        String addrpro = prisonerSr.getAddrpro();
        String addrcity = prisonerSr.getAddrcity();
        String addrcou = prisonerSr.getAddrcou();
        String addrvil = prisonerSr.getAddrvil();
        if (StringUtils.isNotBlank(addrpro)){
            Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(addrpro,addrcity,addrcou,addrvil);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerSr.setAddrproname(areaNames.get("shengName"));
            prisonerSr.setAddrcityname(areaNames.get("dishiName"));
            prisonerSr.setAddrcouname(areaNames.get("quxianName"));
            prisonerSr.setAddrvilname(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(addrcity)){
                prisonerSr.setAddrcityname("");
            }
            if (StringUtils.isBlank(addrcou)){
                prisonerSr.setAddrcouname("");
            }
            if (StringUtils.isBlank(addrvil)){
                prisonerSr.setAddrvilname("");
            }
        } else {
            prisonerSr.setAddrproname("");
            prisonerSr.setAddrcityname("");
            prisonerSr.setAddrcouname("");
            prisonerSr.setAddrvilname("");
        }
        prisonerSr.setAdduserid(user.getDepartid());
        prisonerSr.setCreateTime(date);
        prisonerSr.setCreateUser(user.getAccount());
        prisonerSr.setUpdateTime(date);
        prisonerSr.setUpdateUser(user.getAccount());
        String addr = prisonerSr.getAddrproname() + prisonerSr.getAddrcityname() + prisonerSr.getAddrcouname() + prisonerSr.getAddrvilname() + prisonerSr.getAddrdetail();
        prisonerSr.setAddr(addr);
        prisonerSr.setId(IdGen.strid());
        // 山西个性化需求
        String localCode = CodeUrlUtils.getLocalCode();
        if(Constants.XzqhCode.SHAN1XI.equals(localCode) && StringUtils.equals(user.getLevel(),Constants.OrgLevel.LEVEL_SFS)){
            checkChangePrisonerSr(prisonerSr, user, Constants.SqlType.INSERT);
        }
        boolean insert = prisonerSr.insert();
        boolean tag = saveInfo(prisonerSr.getPriNum(),4,1);
        if(tag && insert) {
            return Result.success(prisonerSr.getId());
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 更新社会关系
     * @param data data
     * @param user user
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updataSrInfo(String data,UserDTO user) {
        // 对信息进行二次处理
        PrisonerSr prisonerSr = JsonUtil.toBean(data,PrisonerSr.class);
        String name = prisonerSr.getThename().trim();
        prisonerSr.setThename(name);
        if(prisonerSr.getIdnumber().trim().length() <= Constants.Number.NUM_EIGHTEEN) {
            prisonerSr.setIdnumber(Sm4.encryptEcb(prisonerSr.getIdnumber()));
        }
        String addrpro = prisonerSr.getAddrpro();
        String addrcity = prisonerSr.getAddrcity();
        String addrcou = prisonerSr.getAddrcou();
        String addrvil = prisonerSr.getAddrvil();
        if (StringUtils.isNotBlank(addrpro)){
            Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(addrpro,addrcity,addrcou,addrvil);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerSr.setAddrproname(areaNames.get("shengName"));
            prisonerSr.setAddrcityname(areaNames.get("dishiName"));
            prisonerSr.setAddrcouname(areaNames.get("quxianName"));
            prisonerSr.setAddrvilname(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(addrcity)){
                prisonerSr.setAddrcityname("");
            }
            if (StringUtils.isBlank(addrcou)){
                prisonerSr.setAddrcouname("");
            }
            if (StringUtils.isBlank(addrvil)){
                prisonerSr.setAddrvilname("");
            }
        } else {
            prisonerSr.setAddrproname("");
            prisonerSr.setAddrcityname("");
            prisonerSr.setAddrcouname("");
            prisonerSr.setAddrvilname("");
        }
        prisonerSr.setUpdateTime(new Date());
        prisonerSr.setUpdateUser(user.getAccount());
        // 山西个性化需求
        String localCode = CodeUrlUtils.getLocalCode();
        if(Constants.XzqhCode.SHAN1XI.equals(localCode) && StringUtils.equals(user.getLevel(),Constants.OrgLevel.LEVEL_SFS)){
            checkChangePrisonerSr(prisonerSr, user,Constants.SqlType.UPDATE);
        }
        int row = prisonerSrMapper.updateById(prisonerSr);
        if(Constants.Number.NUM_ZERO < row) {
            String idstr = prisonerSr.getId();
            return Result.success(idstr);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 更新社会关系excel
     * @param data data
     * @param user user
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updataSrInfoExcel(String data,UserDTO user) {
        // 对信息进行二次处理
        PrisonerSrExcelTemp prisonerSr = JsonUtil.toBean(data,PrisonerSrExcelTemp.class);
        if(prisonerSr.getIdnumber().trim().length() <= Constants.Number.NUM_EIGHTEEN) {
            prisonerSr.setIdnumber(Sm4.encryptEcb(prisonerSr.getIdnumber()));
        }
        if(prisonerSr.getIdType() != null) {
            prisonerSr.setSrIdtype(prisonerSr.getIdType());
        }
        String name = prisonerSr.getThename().trim();
        prisonerSr.setUpdateUser(user.getAccount());
        prisonerSr.setUpdateTime(new Date());
        prisonerSr.setThename(name);
        String addrpro = prisonerSr.getAddrpro();
        String addrcity = prisonerSr.getAddrcity();
        String addrcou = prisonerSr.getAddrcou();
        String addrvil = prisonerSr.getAddrvil();
        if (StringUtils.isNotBlank(addrpro)){
            Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(addrpro,addrcity,addrcou,addrvil);
            if (areaNames == null){
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerSr.setAddrproname(areaNames.get("shengName"));
            prisonerSr.setAddrcityname(areaNames.get("dishiName"));
            prisonerSr.setAddrcouname(areaNames.get("quxianName"));
            prisonerSr.setAddrvilname(areaNames.get("jiedaoName"));
            if (StringUtils.isBlank(addrcity)){
                prisonerSr.setAddrcityname("");
            }
            if (StringUtils.isBlank(addrcou)){
                prisonerSr.setAddrcouname("");
            }
            if (StringUtils.isBlank(addrvil)){
                prisonerSr.setAddrvilname("");
            }
        } else {
            prisonerSr.setAddrproname("");
            prisonerSr.setAddrcityname("");
            prisonerSr.setAddrcouname("");
            prisonerSr.setAddrvilname("");
        }
        prisonerSr.setCheckFlag("0");
        int row = prisonerSrExcelTempMapper.updateById(prisonerSr);
        if(Constants.Number.NUM_ZERO < row) {
            //mainCount>0说明数据未填写完整
            //mainCount=0说明数据已经完整
            //当下面四个值都为0就设置主表的success_flag=0；
            int mainCount = prisonerMainExcelTempMapper.selectMainByCheckFlag(prisonerSr.getPriNum());
            int fxCount = prisonerFxExcelTempMapper.selectFxByCheckFlag(prisonerSr.getPriNum());
            int znCount = prisonerZnExcelTempMapper.selectZnByCheckFlag(prisonerSr.getPriNum());
            if(Constants.Number.NUM_ZERO.equals(mainCount + fxCount + znCount)) {
                prisonerMainExcelTempMapper.updateMainSuccessFlag(prisonerSr.getPriNum());
            }
            String idstr = prisonerSr.getId();
            return Result.success(idstr);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 预安置人员信息录入 - 社会关系 - 配偶、父母或其他 - 列表
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param priNum 罪犯编号
     * @return String
     */
    @Override
    public String getSrList(Integer pageIndex,Integer pageSize,
                            @Converse(caseIf = "-1", converseTo = "0") String priNum) {
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page = page.setRecords(prisonerSrMapper.getSrInfo(page,priNum));
        //处理手机号和电话号码-----by pzc -------0801-----end
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 预安置人员信息录入 - 社会关系 - 配偶、父母或其他 - 列表excel
     * @param pageIndex 当前页
     * @param pageSize 每页数据量
     * @param priNum 罪犯编号
     * @return String
     */
    @Override
    public String getSrListExcel(Integer pageIndex,Integer pageSize,
                                 @Converse(caseIf = "-1", converseTo = "0") String priNum) {
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page = page.setRecords(prisonerSrExcelTempMapper.getSrInfo(page,priNum));
        return JsonUtil.toText(page.getTotal(),DataUtils.handlePhone(page.getRecords(),"tel"));
    }

    /**
     * 根据ID查询社会关系 - 配偶、父母或其他信息
     * @param id id
     * @return String
     */
    @Override
    public String getSrInfoById(String id) {
        PrisonerSr p = prisonerSrMapper.selectById(id);
        String text = JsonUtil.toText(p);
        Map<String,Object> map = JsonUtil.toMap(text);
        String idstr = map.get("id").toString();
        map.put("id",idstr);
        return JsonUtil.toText(map);
    }

    /**
     * 根据ID查询社会关系 - 配偶、父母或其他信息excel
     * @param id id
     * @return String
     */
    @Override
    public String getSrInfoByIdExcel(String id) {
        PrisonerSrExcelTemp p = prisonerSrExcelTempMapper.selectById(id);
        String text = JsonUtil.toText(p);
        Map<String,Object> map = JsonUtil.toMap(text);
        String idstr = map.get("id").toString();
        if(map.get("srIdtype") != null) {
            map.put("idType",map.get("srIdtype"));
        }
        map.put("id",idstr);
        return JsonUtil.toText(map);
    }

    /**
     * 删除社会关系信息（逻辑删除）
     * @param id id
     * @param priNum 罪犯编号
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteSrInfo(String id,String priNum) {
        int row = prisonerSrMapper.updateFlag(id);
        boolean tag = true;
        // 当配偶，父母或者其他关系的人数为空的时候，更改状态
        List<PrisonerSr> list = prisonerSrMapper.getListByPrinum(priNum);
        if(list.isEmpty()) {
            // 更新核查状态，以及中间表中的状态
            tag = saveInfo(priNum,4,0);
        }
        if(Constants.Number.NUM_ZERO < row && tag) {
            return Result.success("删除成功");
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 删除社会关系信息（逻辑删除）excel
     * @param id id
     * @param priNum 罪犯编号
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteSrInfoExcel(String id,String priNum) {
        int row = prisonerSrExcelTempMapper.deleteById(id);
        if(Constants.Number.NUM_ZERO < row) {
            return Result.success("删除成功");
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 插入的社会关系信息的时候，会操作多张表
     * @param priNum 罪犯编号
     * @param num 缓存表列序号 1主表 2服刑表 3zz表 4社会关系表
     * @param val 要设置的值
     * @return boolean
     */
    public boolean saveInfo(String priNum,Integer num,Integer val) {
        boolean flag;
        // 更新中间表的状态
        PrisaveTemp pt = new PrisaveTemp();
        PrisaveTemp prisaveTemp = prisaveTempMapper.selectById(priNum);
        if(null == prisaveTemp) {
            pt.setId(IdGen.strid());
        }
        pt.setPriNum(priNum);
        if(num.equals(Constants.SavePrivateTempFlag.MAINFLAG)) {
            pt.setMainFlag(Constants.Number.NUM_ONE);
        } else if(num.equals(Constants.SavePrivateTempFlag.FXFLAG)) {
            pt.setFxFlag(Constants.Number.NUM_ONE);
        } else if(num.equals(Constants.SavePrivateTempFlag.ZZFLAG)) {
            pt.setZzFlag(Constants.Number.NUM_ONE);
        } else if(num.equals(Constants.SavePrivateTempFlag.SRFLAG)) {
            pt.setSrFlag(val);
        }
        flag = pt.insertOrUpdate();
        return flag && updateState(priNum);
    }

    /**
     * 更新主表状态
     * @param prinum 罪犯编号
     * @return boolean
     */
    public boolean updateState(String prinum) {
        //根据犯罪编号查询主表
        PrisonerMain pm = prisonerMainMapper.selectPrisonerMain(prinum);
        pm.setUpdateTime(new Date());
        //如果当前罪犯状态为：信息未录入完整、待核查
        if(Constants.State.WEILURUWANZHENG_STATE.equals(pm.getState()) || Constants.State.DAIHECHA_STATE.equals(pm.getState())) {
            PrisaveTemp prisaveTemp = prisaveTempMapper.selectById(prinum);
            int row = -1;
            if(null != prisaveTemp) {
                int i = prisaveTemp.getMainFlag() + prisaveTemp.getFxFlag() + prisaveTemp.getSrFlag() + prisaveTemp.getZzFlag();
                if(Constants.Number.NUM_FOUR == i) {
                    row = prisonerMainMapper.updateStateByPrinum(prinum,Constants.NumberStr.NUM_STR_ONE);
                } else {
                    row = prisonerMainMapper.updateStateByPrinum(prinum,Constants.NumberStr.NUM_STR_ZERO);
                }
            }
            return -1 != row;
        }
        return true;
    }

    /**
     * 描述
     * @param prinum 罪犯编号
     * @return PrisonerMain
     */
    @Override
    public PrisonerMain getPriMainByPrinum(String prinum) {
        return prisonerMainMapper.selectById(prinum);
    }

    /**
     * 山西个性化需求:检查是否更改社会关系信息
     * @param prisonerSr prisonerSr
     * @param user user
     * @param type type
     * @return boolean
     */
    private boolean checkChangePrisonerSr(PrisonerSr prisonerSr,UserDTO user,String type) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        //查询出当前库中的对象信息
        PrisonerSr prisonerSr1 = prisonerSrMapper.selectPrisonerSrById(prisonerSr.getId());
        if(null != prisonerSr1 && !StringUtils.isEmpty(prisonerSr1.getIdnumber())) {
            prisonerSr1.setIdnumber(Sm4.decryptEcb(prisonerSr1.getIdnumber()));
        }
        if(null == prisonerSr1) {
            prisonerSr1 = new PrisonerSr();
        }
        //比较前端传的参数对象和数据库对象是否一致prisonerMain、prisonerInfoByPrinm
        String[] ignoreFields = {"id","priNum","adduserid","delFlag","createUser","createTime","updateUser","updateTime"};
        String newTel = prisonerSr.getTel();
        String newtel = "";
        String newphone = "";
        String oldtel = "";
        String oldphone = "";
        //修改之后的电话号码
        if(newTel.contains("|")) {
            newtel = newTel.substring(0,newTel.indexOf("|"));
            newphone = newTel.substring(newTel.indexOf("|") + 1);
        } else if(PhoneUtil.isMobile(newTel)) {
            newtel = newTel;
        } else if(PhoneUtil.phone(newTel)) {
            newphone = newTel;
        }
        Map<String,List<Object>> stringListMap = CheckFieldValue.compareFields(prisonerSr,prisonerSr1,ignoreFields);
        Iterator it = stringListMap.keySet().iterator();
        if(Constants.SqlType.INSERT.contentEquals(type)) {
            //如果是新增则直接添加数据库
            if(!StringUtils.isEmpty(newtel)) {
                changeTableMapper.saveChange(prisonerSr.getId(),"prisoner_sr","phone",oldtel,user.getAccount() + ":" + newtel);
            } else if(!StringUtils.isEmpty(newphone)) {
                changeTableMapper.saveChange(prisonerSr.getId(),"prisoner_sr","tel",oldphone,user.getAccount() + ":" + newphone);
            }
            while(it.hasNext()) {
                String key;
                List<Object> value;
                key = it.next().toString();
                value = stringListMap.get(key);
                if("idnumber".equals(key) && Sm4.encryptEcb(Constants.StrFinalValue.WU).equals(value.get(0))) {
                    continue;
                }
                //新增
                changeTableMapper.saveChange(prisonerSr.getId(),"prisoner_sr",key,String.valueOf(value.get(1)),user.getAccount() + ":" + String.valueOf(value.get(0)));
            }
            return true;
        }
        String oldTel = prisonerSr1.getTel();
        //未修改之前的电话号码
        if(oldTel.contains("|")) {
            oldtel = oldTel.substring(0,oldTel.indexOf("|"));
            oldphone = oldTel.substring(oldTel.indexOf("|") + 1);
        }
        if(!StringUtils.equals(oldphone,newphone)) {
            List<ChangeTable> changeTables = changeTableMapper.searchChangePriNum(prisonerSr1.getId(),"prisoner_sr","phone");
            if(null == changeTables || 0 == changeTables.size()) {
                changeTableMapper.saveChange(prisonerSr.getId(),"prisoner_sr","phone",oldphone,user.getAccount() + ":" + newphone);
            } else {
                changeTableMapper.updateChangeValue(prisonerSr.getId(),"prisoner_sr","phone",oldphone,changeTables.get(0)
                                                                                                                  .getChangeValue() + "," + user.getAccount() + ":" + newphone,changeTables.get(0)
                                                                                                                                                                                           .getId());
            }
        }
        if(!StringUtils.equals(newtel,oldtel)) {
            List<ChangeTable> changeTables = changeTableMapper.searchChangePriNum(prisonerSr1.getId(),"prisoner_sr","tel");
            if(null == changeTables || 0 == changeTables.size()) {
                changeTableMapper.saveChange(prisonerSr.getId(),"prisoner_sr","tel",oldtel,user.getAccount() + ":" + newtel);
            } else {
                changeTableMapper.updateChangeValue(prisonerSr.getId(),"prisoner_sr","tel",oldtel,changeTables.get(0)
                                                                                                              .getChangeValue() + "," + user.getAccount() + ":" + newtel,changeTables.get(0)
                                                                                                                                                                                     .getId());
            }
        }
        while(it.hasNext()) {
            String key;
            List<Object> value;
            key = it.next().toString();
            value = stringListMap.get(key);
            List<ChangeTable> changeTables = changeTableMapper.searchChangePriNum(prisonerSr.getId(),"prisoner_sr",key);
            if(changeTables.size() > 0) {
                if(value.get(1) instanceof Date) {
                    // 日期单独处理
                    changeTableMapper.updateChangeValue(prisonerSr.getId(),"prisoner_sr",key,format.format(value.get(1)),changeTables.get(0)
                                                                                                                                     .getChangeValue() + "," + user.getAccount() + ":" + format.format(value.get(0)),changeTables.get(0)
                                                                                                                                                                                                                                 .getId());
                } else {
                    //追加
                    changeTableMapper.updateChangeValue(prisonerSr.getId(),"prisoner_sr",key,String.valueOf(value.get(1)),changeTables.get(0)
                                                                                                                                      .getChangeValue() + "," + user.getAccount() + ":" + String.valueOf(value.get(0)),changeTables.get(0)
                                                                                                                                                                                                                                   .getId());
                }
            } else {
                if(value.get(1) instanceof Date) {
                    // 日期单独处理
                    changeTableMapper.saveChange(prisonerSr.getId(),"prisoner_sr",key,format.format(value.get(1)),user.getAccount() + ":" + format.format(value.get(0)));
                } else {
                    //新增
                    changeTableMapper.saveChange(prisonerSr.getId(),"prisoner_sr",key,String.valueOf(value.get(1)),user.getAccount() + ":" + String.valueOf(value.get(0)));
                }
            }
        }
        return true;
    }

    /**
     * 山西个性化需求:检查是否更改未成年子女信息
     * @param prisonerZn prisonerZn
     * @param user user
     * @param type type
     * @return boolean
     */
    private boolean checkChangePrisonerZn(PrisonerZn prisonerZn, UserDTO user, String type) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        //查询出当前库中的对象信息
        PrisonerZn prisonerZnPriNum = prisonerZnMapper.selectPrisonerZnById(prisonerZn.getId());
        if(null != prisonerZnPriNum && !StringUtils.isEmpty(prisonerZnPriNum.getZnsfId())){
            //身份证解密
            prisonerZnPriNum.setZnsfId(Sm4.decryptEcb(prisonerZnPriNum.getZnsfId()));
        }

        if(null == prisonerZnPriNum){
            prisonerZnPriNum = new PrisonerZn();
        }
        //比较前端传的参数对象和数据库对象是否一致prisonerMain、prisonerInfoByPrinm
        String[] ignoreFields = {"id","priNum","adduserid","delFlag","createUser","createTime","updateUser","updateTime"};
        Map<String, List<Object>> stringListMap = CheckFieldValue.compareFields(prisonerZn, prisonerZnPriNum, ignoreFields);
        Iterator it=stringListMap.keySet().iterator();
        if(Constants.SqlType.INSERT.contentEquals(type)){
            while(it.hasNext()){
                String key;
                List<Object> value;
                key=it.next().toString();
                value=stringListMap.get(key);
                if("znsfId".equals(key) && Sm4.encryptEcb(Constants.StrFinalValue.WU).equals(value.get(0))) {
                    continue;
                }
                //新增
                changeTableMapper.saveChange(prisonerZn.getId(),"prisoner_zn",key,String.valueOf(value.get(1)),user.getAccount()+":"+String.valueOf(value.get(0)));
            }
            return true;
        }
        while(it.hasNext()){
            String key;
            List<Object> value;
            key=it.next().toString();
            value=stringListMap.get(key);
            List<ChangeTable> changeTables = changeTableMapper.searchChangePriNum(prisonerZn.getId(), "prisoner_zn", key);

            if(0 < changeTables.size()){
                if(value.get(1) instanceof Date) {
                    //追加
                    changeTableMapper.updateChangeValue(prisonerZn.getId(),"prisoner_zn",key,format.format(value.get(1)),changeTables.get(0).getChangeValue()+ ","+user.getAccount()+":"+format.format(value.get(0)),
                            changeTables.get(0).getId());
                } else{
                    //追加
                    changeTableMapper.updateChangeValue(prisonerZn.getId(),"prisoner_zn",key,String.valueOf(value.get(1)),changeTables.get(0).getChangeValue()+ ","+user.getAccount()+":"+String.valueOf(value.get(0)),
                            changeTables.get(0).getId());
                }
            } else {
                if(value.get(1) instanceof Date) {
                    //新增
                    changeTableMapper.saveChange(prisonerZn.getId(),"prisoner_zn",key,format.format(value.get(1)),user.getAccount()+":"+format.format((value.get(0))));
                } else {
                    changeTableMapper.saveChange(prisonerZn.getId(),"prisoner_zn",key,String.valueOf(value.get(1)),user.getAccount()+":"+String.valueOf(value.get(0)));
                }
            }
        }
        return true;
    }
}